package com.zb.filter;

import com.zb.dto.LoginUser;
import com.zb.exceptions.BussinessException;
import com.zb.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class PowerFilter extends OncePerRequestFilter {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        System.out.println("进入拦截器.....");
        //获取令牌
        String token = httpServletRequest.getHeader("token");
        //验证令牌必须是字符串类型
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        //验证令牌的有效性
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BussinessException("令牌失效!");
        }
        //验证redis中是否存在令牌的数据
        LoginUser loginUser = (LoginUser) redisTemplate.boundValueOps("login:" + claims.getSubject()).get();
        if (ObjectUtils.isEmpty(loginUser)) {
            throw new BussinessException("没有数据!");
        }
        //将用户的信息存储到认证框架中表示， 用户已经登录成功！
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        //放行接口
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
